package com.member.server.domain;

import com.alibaba.fastjson.JSON;

import java.io.Serializable;

/**
 * @author junxiang.gao
 * @since 2021/11/3
 */
public final class Result<T> implements Serializable {

    public static final int SUCCESS = 200;
    public static final int FAIL = 400;

    public static final String CODE_TAG = "code";

    public static final String MESSAGE_TAG = "message";

    public static final String DATA_TAG = "data";

    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    private int code;

    /**
     * 信息
     */
    private String message;

    /**
     * 数据
     */
    private T data;

    /**
     * 默认构造函数
     */
    public Result() {

    }

    public Result(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }

    public boolean isSuccess() {
        return code == SUCCESS;
    }

    public static <T> Result<T> success() {
        return build(SUCCESS, "success", null);
    }

    public static <T> Result<T> success(T data) {
        return build(SUCCESS, "success", data);
    }

    public static <T> Result<T> fail(String message) {
        return build(FAIL, message, null);
    }

    public static <T> Result<T> fail(String message, T data) {
        return build(FAIL, message, data);
    }

    public static <T> Result<T> build(int errorCode, String message, T data) {
        return new Result<>(errorCode, message, data);
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
